<?php

class autocurrency extends Controller
{
    public function run($params = null)
    {
        if ($this->config->get('currency_fixer_status')) {
            $currencies = array();
            $this->load->model('localisation/currency');
            $default = $this->config->get('config_currency');

            $results = $this->model_localisation_currency->getCurrencies();

            foreach ($results as $result) {
                if (($result['code'] != $default)) {
                    $currencies[] = $result;
                }
            }

            if ($currencies) {
                $str_curres = join(',', array_column($currencies, 'code'));
                $url = "https://api.apilayer.com/currency_data/live?source=$default&currencies=" . $str_curres;
                echo $url . PHP_EOL;

                $curl = curl_init();

                curl_setopt_array($curl, array(
                    CURLOPT_URL => $url,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_SSL_VERIFYPEER => false,
                    CURLOPT_SSL_VERIFYHOST => false,
                    CURLOPT_ENCODING => '',
                    CURLOPT_MAXREDIRS => 10,
                    CURLOPT_TIMEOUT => 60,
                    CURLOPT_FOLLOWLOCATION => true,
                    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                    CURLOPT_CUSTOMREQUEST => 'GET',
                    CURLOPT_HTTPHEADER => array(
                        'apikey: D4Pg2SOMgQpBSgWwHR05LKDz7VWnUiEe'
                    ),
                ));

                $response = curl_exec($curl);

                curl_close($curl);
                echo $response;

                $response_info = json_decode($response, true);

                if (isset($response_info['quotes'])) {
                    foreach ($currencies as $currency) {
                        if (isset($response_info['quotes'][$default . $currency['code']])) {
                            $this->model_localisation_currency->editValueByCode($currency['code'], $response_info['quotes'][$default . $currency['code']]);
                        }
                    }
                }

                $this->cache->delete('currency');
            }

            $this->model_localisation_currency->editValueByCode($default, '1.00000');
            echo 'success';
        }
    }
}